/**
 * Name:tool.js
 * Author:gene.jiang
 * E-mail:1013195469@qq.com
 * Website:http://www.jianggujin.com/
 * LICENSE:Apache v2 License
 * Description:选项卡
 */
layui.define(['jquery', 'element', 'nprogress', 'tool', 'layer', 'geneconfig'], function(exports) {
    var $ = layui.jquery,
        _geneconfig_ = layui.geneconfig,
        _element_ = layui.element,
        _tool_ = layui.tool,
        _body_ = $('body'),
        _win_ = $(window),
        _resizeId_ = -1,
        //Safari浏览器选项卡切换后会出现鼠标滚动无效，只能拖拽滚动条的情况
        //这里的解决方案为设置iframe的高度为内容高度，外部div滚动
        _safari_ = 'Safari' === _tool_.getExplore().name,
        _contentHeight_ = 0,
        _frameCache_ = {};

    layui.link(_geneconfig_.getModulePath() + '/css/tab.css');

    function setIframeHeight(iframe) {
        if(iframe) {
            var iframeWin = iframe.contentWindow || iframe.contentDocument.parentWindow;
            if(iframeWin.document.body) {
                var height = iframeWin.document.documentElement.scrollHeight || iframeWin.document.body.scrollHeight;
                height = Math.max(_contentHeight_, height) - 4;
                if(height != parseInt(iframe.style.height)) {
                    iframe.style.height = height + 'px';
                }
            }
        }
    };

    function triggerTabChange(tab, parents, filter) {
        var othis = $(tab),
            index = othis.parent().children('li').index(othis);
        parents = parents || othis.parents('.layui-tab').eq(0);
        filter = filter || parents.attr('lay-filter');

        layui.event.call(othis[0], 'element', 'tab(' + filter + ')', {
            elem: parents,
            index: index
        });
    }

    var Tab = function(options) {
        this.__render(options);
    };
    Tab.fn = Tab.prototype;
    Tab.fn.getFilter = function() {
        return this._filter;
    };
    Tab.fn.__render = function(options) {
        if(this._initialized) {
            layui.hint().error('Tab已经初始化！');
            return;
        }
        options = options || {};

        if(!!options.elem) {
            this._container = $(options.elem);
            //存在配置的容器
            if(!this._container.length) {
                this._container = undefined;
            }
        }
        if(!this._container) {
            //选取默认容器
            this._container = _body_.find('div[gene-tab]');
        }
        if(!this._container || !this._container.length) {
            layui.hint().error('Tab没有正常初始化！');
            return;
        }
        this._container = this._container.eq(0);

        this._toolEnable = false;
        this._filter = options.filter || _tool_.makeHashCode('geneTab');

        var _that = this,
            _elem = _that._container,
            _title = _that._title = $('<ul class="layui-tab-title"></ul>'),
            _content = _that._content = $('<div class="layui-tab-content"></div>'),
            _tool = _that._tool = $('<div class="gene-tab-tool"><i class="layui-icon">&#xe671;</i></div>'),
            _toolBody = _that._toolBody = $('<div class="gene-tab-tool-body layui-anim layui-anim-upbit"></div>'),
            //工具项
            _toolRefresh = _that._toolRefresh = $('<li class="gene-item">刷新当前选项卡</li>'),
            _toolClose = _that._toolClose = $('<li class="gene-item">关闭当前选项卡</li>'),
            _toolCloseOther = _that._toolCloseOther = $('<li class="gene-item">关闭其他选项卡</li>'),
            _toolCloseAll = _that._toolCloseAll = $('<li class="gene-item">关闭所有选项卡</li>'),
            _toolItemContainer = $('<ul></ul>'),
            _tabSwitch = typeof options.tabSwitch === 'function' ? options.tabSwitch : $.noop,
            _tabDelete = typeof options.tabDelete === 'function' ? options.tabDelete : $.noop;
        _elem.empty();
        _elem.attr('lay-filter', _that._filter);
        _elem.addClass('layui-tab layui-tab-card gene-tab');
        _elem.append(_title);
        _elem.append(_tool);
        _toolItemContainer.append(_toolRefresh);
        _toolItemContainer.append(_toolClose);
        _toolItemContainer.append(_toolCloseOther);
        _toolItemContainer.append(_toolCloseAll);
        _toolBody.append(_toolItemContainer);
        _tool.append(_toolBody);
        _elem.append(_content);

        var _timeoutIndex = -1;
        _tool.on('mouseenter', function() {
            clearTimeout(_timeoutIndex);
            if(_that._toolEnable) {
                _timeoutIndex = setTimeout(function() {
                    _toolBody.addClass('layui-show');
                }, 300);
            }
        }).on('mouseleave', function() {
            clearTimeout(_timeoutIndex);
            _timeoutIndex = setTimeout(function() {
                _toolBody.removeClass('layui-show');
            }, 300);
        });
        _toolRefresh.on('click', function() {
            _that.refresh();
        });

        _toolClose.on('click', function() {
            _that.close();
        });
        _toolCloseOther.on('click', function() {
            _that.closeOther();
        });
        _toolCloseAll.on('click', function() {
            _that.closeAll();
        });

        _win_.on('resize', function() {
            var currBoxHeight = _elem.height();
            if(_safari_) {
                //_that._content.find('.layui-tab-item').height(currBoxHeight - 41);
                _contentHeight_ = currBoxHeight - 41;
                _that._content.height(_contentHeight_);
            } else {
                _that._content.find('iframe').height(currBoxHeight - 41);
            }
        }).resize();

        if(_safari_) {
            setInterval(function() {
                for(var f in _frameCache_) {
                    setIframeHeight(_frameCache_[f]);
                }
            }, options.frameHeightRefresh || 500);
        }
        _element_.init('tab', _that._filter);
        _element_.on('tab(' + _that._filter + ')', function(data) {
            var $this = $(this);
            _tabSwitch($this, $this.attr('lay-id'), data.index);
        });
        _element_.on('tabDelete(' + _that._filter + ')', function(data) {
            var $this = $(this);
            _tabDelete($this, $this.attr('lay-id'), data.index);
        });
        _that._initialized = true;
        return _that;
    };
    Tab.fn.getLayId = function() {
        return this._title.find('li.layui-this').attr('lay-id');
    };
    Tab.fn.close = function() {
        var layId = this.getLayId();
        this.tabDelete(layId);
    };
    Tab.fn.refresh = function() {
        var layId = this.getLayId(),
            _that = this;
        var item = this._content.children('div[lay-item-id=' + layId + ']').children('iframe');
        //      var src = item.attr('src');
        //      if(src) {
        //          if(src.indexOf('?') > 0) {
        //              src += '&';
        //          } else {
        //              src += '?';
        //          }
        //          src += '_v_timpe_=' + new Date().getTime();
        //      }
        //      item.attr('src', src);
        item[0].contentWindow.location.reload(true);
    };

    Tab.fn.closeOther = function() {
        var layId = this.getLayId(),
            _that = this;
        this._title.children('li[lay-id]').each(function() {
            var curId = $(this).attr('lay-id');
            if(curId != layId) {
                _that.tabDelete(curId, false);
            }
        });
        _that.__sync();
    };
    Tab.fn.closeAll = function() {
        var _that = this;
        this._title.children('li[lay-id]').each(function() {
            var curId = $(this).attr('lay-id');
            _that.tabDelete(curId, false);
        });
        _that.__sync();
    };
    Tab.fn.tabCount = function() {
        return this._title.find('li[lay-id]').length;
    };
    Tab.fn.getTab = function(layId) {
        return this._title.find('li[lay-id=' + layId + ']');
    };
    Tab.fn.getTabContent = function(layId) {
        return this._content.find('div[lay-item-id=' + layId + ']');
    };
    Tab.fn.tabExists = function(layId) {
        return !!this._title.find('li[lay-id=' + layId + ']').length;
    };

    //重写删除
    Tab.fn.tabDelete = function(layId, sync) {
        var _that = this;
        if(this.getTab(layId).is('li[_geneTabCanClose]')) {

            var _tab = _that.getTab(layId),
                _tabContent = _that.getTabContent(layId),
                _index = _tab.index;

            if(_tab.hasClass('layui-this')) {
                var _nTab = _tab.next();
                if(!!!_nTab.length) {
                    _nTab = _tab.prev();
                }
                if(!!_nTab.length) {
                    _that.tabChange(_nTab.attr('lay-id'));
                }
            }

            _tab.remove();
            _tabContent.remove();

            if(_safari_) {
                delete _frameCache_[layId];
            }
            if(_resizeId_ != -1) {
                clearTimeout(_resizeId_);
            }
            _resizeId_ = setTimeout(function() {
                _win_.resize();
            }, 50);

            layui.event.call(_tab[0], 'element', 'tab(' + _that._filter + ')', {
                elem: _that._container,
                index: _index
            });

        }
        if(sync !== false) {
            this.__sync();
        }
    };
    Tab.fn.tabDeleteIndex = function(index) {
        var layId = this._title.find('li[lay-id]').eq(index);
        this.tabDelete(layId);
    };
    Tab.fn.tabChange = function(layId) {
        var _that = this,
            _tab = this.getTab(layId),
            _tabContent = this.getTabContent(layId);
        if(!!_tab.length) {
            _tab.addClass('layui-this').siblings().removeClass('layui-this');
            _tabContent.addClass('layui-show').siblings().removeClass('layui-show');
            triggerTabChange(_tab, _that._container, _that._filter);
        }
    };
    Tab.fn.tabChangeIndex = function(index) {
        var layId = this._title.find('li[lay-id]').eq(index);
        this.tabChange(layId);
    };
    Tab.fn.tabAdd = function(options) {
        options = options || {};
        var _that = this,
            _loadIndex = undefined;
        var _attr = options.attr,
            _title = options.title || '新标签页',
            _icon = options.icon,
            _eIcon = options.eIcon,
            _url = options.url,
            _id = options.id || _tool_.makeHashCode('geneTabItem'),
            _openWait = options.openWait === false ? false : true,
            _canClose = options.canClose === false ? false : true;
        //如果选项卡已经存在，直接切换
        if(_that.tabExists(_id)) {
            _that.tabChange(_id);
            return _id;
        }
        NProgress.start();
        if(_openWait) {
            _loadIndex = _tool_.load();
        }
        var _li = $('<li></li>');
        _li.attr('lay-id', _id);
        if(!!_attr) {
            _li.attr(_attr);
        }
        if(_icon) {
            _li.html('<i class="layui-icon">' + _icon + '</i>');
        } else if(_eIcon) {
            _li.html(_eIcon);
        }
        $('<span></span>').html(_title).appendTo(_li);
        if(_canClose) {
            _li.attr('_geneTabCanClose', '');
            var _i = $('<i class="layui-icon layui-unselect layui-tab-close">&#x1006;</i>');
            _li.append(_i);
            _i.on('click', function() {
                _that.tabDelete(_id);
            });
        }
        var _div = $('<div class="layui-tab-item layui-show"></div>'),
            _iframe = null;
        if(_safari_) {
            _iframe = $('<iframe frameborder="no" border="0" scrolling="no" style="height:0px;"></iframe>');
        } else {
            _iframe = $('<iframe frameborder="no" border="0"></iframe>');
        }
        _div.attr('lay-item-id', _id);
        _iframe.attr('src', _url);
        _div.append(_iframe);
        //追加htm
        _that._title.append(_li);
        _that._content.append(_div);

        _iframe.on('load', function() {
            NProgress.done();
            _openWait && _loadIndex && layer.close(_loadIndex);
            if(_safari_) {
                _frameCache_[_id] = _iframe[0];
            }
        });

        _that.tabChange(_id);
        //触发窗体尺寸改变，延迟一下，否则计算有问题
        setTimeout(function() {
            _win_.resize();
        }, 60);
        _that.__sync();
        return _id;
    };
    /**
     * 同步操作栏状态
     */
    Tab.fn.__sync = function() {
        var _curr = this._title.find('li.layui-this');
        if(!!_curr.length) {
            if(_curr.is('li[_geneTabCanClose]')) {
                this._toolClose.show();
            } else {
                this._toolClose.hide();
            }

            var _cancloseTab = this._title.find('li[_geneTabCanClose]');
            if(!!_cancloseTab.length) {
                this._toolCloseAll.show();
                if(_cancloseTab.length > 1 || _cancloseTab.attr('lay-id') != _curr.attr('lay-id')) {
                    this._toolCloseOther.show();
                } else {
                    this._toolCloseOther.hide();
                }
            } else {
                this._toolCloseAll.hide();
                this._toolCloseOther.hide();
            }
            this._toolEnable = true;

        } else {
            this._toolEnable = false;
            this._toolBody.removeClass('layui-show');
        }
    };
    $(document).off('click', '.layui-tab-title li').on('click', '.layui-tab-title li', function() {
        var othis = $(this),
            parents = othis.parents('.layui-tab').eq(0);

        if(!!othis.length) {
            if(othis.hasClass('layui-this')) {
                return;
            }
            var layId = othis.attr('lay-id');
            othis.addClass('layui-this').siblings().removeClass('layui-this');
            parents.find('div[lay-item-id=' + layId + ']').addClass('layui-show').siblings().removeClass('layui-show');
        }
        triggerTabChange(othis, parents);
    });

    var tab = null;;

    function TabExport() {}
    TabExport.prototype.render = function(options) {
        return new Tab(options);
    }
    exports('tab', new TabExport());
});